package com.atguigu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.bean.TravelGroup;
import com.atguigu.dao.TravelGroupMapper;
import com.atguigu.dao.TravelGroupTravelItemMapper;
import com.atguigu.entity.PageResult;
import com.atguigu.entity.QueryPageBean;
import com.atguigu.service.TravelGroupService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = TravelGroupService.class)
@Transactional
public class TravelGroupServiceImpl implements TravelGroupService {

    @Autowired
    private TravelGroupMapper travelGroupMapper;

    @Autowired
    TravelGroupTravelItemMapper travelGroupTravelItemMapper;

    @Override
    public void add(TravelGroup travelGroup, Integer[] id) {
        //先保存跟团游信息，返回跟团游对应的id
        travelGroupMapper.add(travelGroup);
        //获取跟团游id
        Integer travelGroupId = travelGroup.getId();
        //将跟团游的id和自由行的id添加到中间表中
        travelGroupTravelItemMapper.add(travelGroupId,id);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        List<TravelGroup> travelGroupList = travelGroupMapper.findPage(queryPageBean.getQueryString());
        PageInfo<TravelGroup> pageInfo = new PageInfo<>(travelGroupList);
        PageResult pageResult = new PageResult(pageInfo.getTotal(),pageInfo.getList());
        return pageResult;
    }

    @Override
    public void delete(Integer id) {
        travelGroupMapper.delete(id);
    }

    @Override
    public TravelGroup findById(Integer id) {
        return travelGroupMapper.findById(id);
    }

    @Override
    public List<Integer> getTravelItemIds(Integer id) {
        return travelGroupTravelItemMapper.getTravelItemIds(id);
    }

    @Override
    public void edit(Integer[] ids, TravelGroup travelGroup) {
        //先修改跟团游的表
        travelGroupMapper.edit(travelGroup);
        ////先删除与跟团游相关联的所有的自由行的id
        travelGroupTravelItemMapper.deleteTravelItemIds(travelGroup.getId());
        //再往中间表中添加改跟团游id与自由行id的对应关系
        travelGroupTravelItemMapper.add(travelGroup.getId(),ids);
    }

    @Override
    public List<TravelGroup> findAll() {
        return travelGroupMapper.findAll();
    }
}
